import { login, userInfo, logout } from "@/api/login"
import { TOKEN } from "@/utils/settings"
import router from "@/router"

export default {
  namespaced: true,
  state: {
    token: "",
    userInfo: {}
  },
  mutations: {
    SET_TOKEN: (state, payload) => {
      state.token = payload
    },
    SET_USERINFO: (state, payload) => {
      state.userInfo = payload
    }
  },
  actions: {
    loginAction({ commit, dispatch }, payload) {
      return new Promise((resolve, reject) => {
        const data = {
          username: payload.username,
          password: payload.password
        }
        const params = {
          captchaVerification: payload.captchaVerification
        }
        login(data, params)
          .then((res) => {
            commit("SET_TOKEN", res.data.tokenValue)
            localStorage.setItem(TOKEN, res.data.tokenValue)

            //使用token请求请求相关信息
            dispatch("getUserInfoAction")
            dispatch("permission/getRouteAction", {}, { root: true })
            resolve()
          })
          .catch((err) => {
            reject(err)
          })
      })
    },

    // get user info
    getUserInfoAction({ commit }) {
      userInfo().then((res) => {
        commit("SET_USERINFO", res.data)
      })
    },

    // user logout
    logoutAction() {
      return new Promise((resolve, reject) => {
        logout()
          .then(() => {
            resolve()
          })
          .catch((error) => {
            reject(error)
          })
      })
    },

    getInitialDataAction({ commit, dispatch }) {
      const token = localStorage.getItem(TOKEN)
      if (token) {
        commit("SET_TOKEN", token)
        dispatch("getUserInfoAction")
        dispatch("permission/getRouteAction", {}, { root: true })
      } else {
        router.push("/")
      }
    }
  }
}
